package nancal.mp.nexus


import nancal.mp.nexus.utils.NexusWork
import nbcp.base.extend.*
import nbcp.base.json.*
import nbcp.base.extend.*
import nbcp.base.json.*
import nbcp.base.extend.*
import nbcp.base.json.*
import nbcp.base.utils.MyUtil
import org.slf4j.LoggerFactory
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.context.annotation.Condition
import org.springframework.context.annotation.ConditionContext
import org.springframework.context.annotation.Conditional
import org.springframework.core.type.AnnotatedTypeMetadata
import org.springframework.scheduling.annotation.Scheduled
import org.springframework.stereotype.Component
import java.time.Duration
import java.time.LocalDateTime


class ExistsNexusConfigCondition : Condition {
    override fun matches(context: ConditionContext, metadata: AnnotatedTypeMetadata): Boolean {
        if (context.environment.activeProfiles.contains("dev") == false) {
            return false;
        }
        if (context.environment.getProperty("nexus.from.url").isNullOrEmpty()) {
            return false;
        }

        if (context.environment.getProperty("nexus.targets.0.url").isNullOrEmpty()) {
            return false;
        }

        if (System.getenv("MAVEN_HOME").isNullOrEmpty()) {
            return false;
        }
        return true
    }
}

/**
 * 仅开发环境有效
 */
@Component
@Conditional(ExistsNexusConfigCondition::class)
open class NexusTask {
    companion object {
        fun execTask() {
            triggered = true;
        }

        var working = false
            private set;

        var triggered = false
            private set;

        private var lastExecuteAt = LocalDateTime.MIN;
        var taskLastExecAt = LocalDateTime.now()
            private set;

        private val logger = LoggerFactory.getLogger(this::class.java.declaringClass)
    }

    @Autowired
    lateinit var nexusWork: NexusWork;

    fun needExec(): Boolean {
        var now = LocalDateTime.now();
        if (triggered) {
            triggered = false;
            lastExecuteAt = now;
            return true;
        }

        if (now.hour.IfRangeTo(1, 8)) {
            if (Duration.between(lastExecuteAt, now).toHours() > 12) {

                Thread.sleep((MyUtil.getRandomNumber(10, 60) * 1000).toLong())
                return true;
            }
        }

        return false;
    }

    /**
     * 每1分判断一次
     */
//    @Scheduled(fixedDelay = 60 * 1000)
    fun work() {
        taskLastExecAt = LocalDateTime.now()
        if (needExec() == false) {
            return;
        }
        working = true;

        logger.Important("NexusTask 开始执行")

        nexusWork.clear();

        //读取仓库数据
        try {
            nexusWork.start()

            logger.Important(
                    """
===========================
任务完成,总耗时: ${Duration.between(taskLastExecAt, LocalDateTime.now()).toSummary()}
===========================
"""
            )

            lastExecuteAt = LocalDateTime.now();
        } catch (e: Exception) {
            logger.error(e.message, e)

            logger.Important(
                    """
===========================
任务失败,将再次重试,总耗时: ${Duration.between(taskLastExecAt, LocalDateTime.now()).toSummary()}
===========================
"""
            )

            triggered = true;
        }
        working = false;
    }

}